let express = require('express')

let router = express.Router()

let db = require('./db')

let bodyParser = require('body-parser')

let urlPar = bodyParser.urlencoded({ extended: true })

router.get('/getlist', async function (req, res) {
    let { search, order = 'id', sort = 'asc', pageSize = 5, currentPage = 0 } = req.query
    
    let sql = `SELECT * FROM classify`
    
    let num = pageSize * currentPage
    
    if (search) {
        sql += `  WHERE name LIKE  '%${search}%'`
    }
    
    sql += `  ORDER BY ${order} ${sort}`
    
    if (num) {
        sql += `  LIMIT ${num},${pageSize}`
    } else {
        sql += `  LIMIT ${currentPage},${pageSize}`
    }
    
    let r = await db.doMysql(sql)
    
    console.log(r)
    
    res.send(db.backText(r))
})

router.post('/postlist', urlPar, async function (req,res) {
    let { name } = req.body

    let sql = `INSERT INTO classify (name) VALUES ('${name}')`

    let r = await db.doMysql(sql)

    res.send(db.postText(r))
})

router.post("/update", urlPar, async function (req, res) {
    let { name, id } = req.body
    let sql = `update classify set name='${name}' where id='${id}'`
    let r = await db.doMysql(sql)
    res.send(db.postText(r))
})

router.get("/delete", async function (req, res) {
    let { id } = req.query
    let sql = `delete from classify where id in (${id})`
    let r = await db.doMysql(sql)
    res.send(db.delText(r))
})

module.exports = router